const express = require('express')
const http = require('http')
const websocketServer = require('websocket').server
const cors = require('cors')

const healthRouter = require('./routes/health')
const studentsRouter = require('./routes/students')
const sessionsRouter = require('./routes/sessions')
const permissionsRouter = require('./routes/permissions')

// 创建 Express 应用
const app = express()

// 创建 http 服务器
const server = http.createServer(app)

// 解决跨域问题
app.use(cors())

// 请求数据处理
app.use(express.json())
app.use(express.urlencoded({ extended: false }))

// 路由
app.use('/api/v1/health', healthRouter)
app.use('/api/v1/students', studentsRouter)
app.use('/api/v1/sessions', sessionsRouter)
app.use('/api/v1/permissions', permissionsRouter)

// 监听
server.listen(3000, () => console.log('server running at http://localhost:3000'))

// websocket server
const sockets = []
let id = 1
const list = []
const wsServer = new websocketServer({
  httpServer: server
})

wsServer.on('request', (request) => {
  console.log('connect.....')
  let connection = request.accept(null, request.origin)
  sockets.push(connection)
  connection.sendUTF(JSON.stringify(list))
  connection.on('close', () => {
    console.log('disconnect...')
    connection = null
    // 释放资源：TODO...
  })
})
const random = (min, max) => Math.floor(Math.random() * (max - min)) + min
const genData = () => {
  list.push({id, time: Date.now(), title: '标题' + (id++)})
  sockets.forEach(socket => {
    socket.sendUTF(JSON.stringify(list))
  })
  setTimeout(genData, random(5, 15) * 1000)
}

genData()
